//  this library.
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:hktk_app/decoration/chapter_expansion_tile.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/my/rank_type_enum.dart';
import 'package:hktk_app/ienum/subject/collection_type_enum.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/my/chaper_tree_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/mine/view_chapter_show_widget.dart';
import 'package:hktk_app/widget/subject/chapter_indent_widget.dart';

/// 我的错题/收藏章节可展开组件
class ViewChapterExpandableWidget extends StatefulWidget {
  /// 对应章节数据
  final ChapterTreeModel chapterModel;

  /// 栏目id
  final String columnId;

  /// 类型
  final RankTypeEnum rankType;

  /// 是否在第一位时打开对应数据
  final bool opening;

  const ViewChapterExpandableWidget({
    super.key,
    required this.chapterModel,
    required this.columnId,
    required this.rankType,
    required this.opening,
  });

  @override
  State<ViewChapterExpandableWidget> createState() =>
      _ViewChapterExpandableWidgetState();
}

class _ViewChapterExpandableWidgetState
    extends State<ViewChapterExpandableWidget> {
  late BuildContext _context;

  /// 控制器
  late ChapterExpansionTileController _controller;

  /// 是否处于打开模式
  late bool _isOpenIt;

  /// 子组件数据，懒加载·
  late List<ChapterTreeModel> _childList;

  /// 数据是否加载完成
  late bool _dataInit;

  @override
  void initState() {
    super.initState();
    debugPrint(
        "viewChapterExpandableWidget 组件 -> initState 方法执行 ===> ${widget.chapterModel.name}");
    debugPrint("");
    _controller = ChapterExpansionTileController();
    _isOpenIt = false;
    _childList = [];
    _dataInit = false;
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (widget.opening) {
        _controller.expand();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint(
        "viewChapterExpandableWidget 组件 -> dispose 方法执行 ===> ${widget.chapterModel.name}");
    debugPrint("");
  }

  @override
  Widget build(BuildContext context) {
    debugPrint(
        "viewChapterExpandableWidget 组件 -> build 方法执行 ===> ${widget.chapterModel.name}");
    debugPrint("");
    _context = context;
    return ChapterExpansionTile(
      controller: _controller,
      // 监听是否打开
      onExpansionChanged: _onChangedFun,
      // 父组件显示样式
      title: _title(),
      // 是否显示分割线
      dividerDisplayTime: DividerDisplayTime.never,
      // 子集组件
      children: _subItems(),
    );
  }

  /// title 组件显示，展开集合标题
  _title() {
    return Column(
      children: [
        _titleTopItem(),
        _indentItem(height: 48),
      ],
    );
  }

  /// 标题显示
  _titleTopItem() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          children: [
            SvgPicture.asset(
              _isOpenIt
                  ? "images/home/course_zk.svg"
                  : "images/home/course_bh.svg",
              width: 32,
              height: 32,
            ),
            hiSpace(width: 16),
            Text(
              widget.chapterModel.name!,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: FontUtil.fontBlack1(28, fontWeight: FontWeight.w500),
            ),
          ],
        ),
        Icon(
          _isOpenIt ? Icons.expand_less : Icons.expand_more,
          size: 40,
        ),
      ],
    );
  }

  /// 子集组件
  _subItems() {
    List<Widget> list = [];
    if (_childList.isNotEmpty) {
      // list.add(_indentItem(height: 48));
      for (int i = 0; i < _childList.length; i++) {
        ChapterTreeModel model = _childList[i];
        if (model.leaf!) {
          // 最后一级
          list.add(
            _indentItem(
              child: ViewChapterShowWidget(
                chapterModel: model,
                rankType: widget.rankType,
              ),
            ),
          );
          // 添加间距
          if (i != _childList.length - 1) {
            list.add(_indentItem(height: 30));
          }
        } else {
          // 不是最后一级
          list.add(_indentItem(
            child: ViewChapterExpandableWidget(
              chapterModel: model,
              columnId: widget.columnId,
              rankType: widget.rankType,
              opening: i == 0,
            ),
          ));
        }
      }
      list.add(_indentItem(height: 48));
    }
    return list;
  }

  /// 缩进组件显示
  _indentItem({
    double? height,
    Widget? child,
  }) {
    return ChapterIndentWidget(
      indent: 17,
      paddingLeft: 17,
      height: height,
      child: child,
    );
  }

  /// 监听是否打开方法
  void _onChangedFun(bool value) {
    debugPrint("viewChapterExpandableWidget 组件 -> ${widget.chapterModel.name} 是否打开 ===> $value");
    if (value && !_dataInit) {
      // 开启加载框
      ToastUtil.loadingBoxShow(_context);
      // 加载数据
      _childrenInit().then((Map<String, dynamic> map) {
        // 结束加载框
        ToastUtil.loadingBoxRemove();
        if (map["suc"]) {
          _isOpenIt = value;
          setState(() {});
        } else {
          // 折叠，不打开
          _controller.collapse();
          ToastUtil.show(context: _context, msg: map["msg"]);
        }
      });
    } else {
      setState(() {
        _isOpenIt = value;
      });
    }
  }

  /// 加载相关数据方法
  Future<Map<String, dynamic>> _childrenInit() async {
    Map<String, dynamic> map = {};
    try {
      // 加载子集数据
      DataModel dataModel = dataUtilComm.dataModel;
      _childList = await MyDao.chapterRecordsTree(
        industryCode: dataModel.industryId,
        examId: dataModel.examId,
        categoryId: dataModel.categoryId,
        collectionType: CollectionTypeEnum.chapter,
        chapterId: widget.chapterModel.id!,
        type: widget.rankType,
        industryName: dataModel.industryName,
        examName: dataModel.examName,
        categoryName: dataModel.categoryName,
        columnId: widget.columnId,
      );
      if (_childList.isEmpty) {
        map["msg"] = "暂无数据";
      }
      _dataInit = true;
      map["suc"] = true;
    } catch (e) {
      debugPrint("viewChapterExpandableWidget 组件 -> 请求发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("viewChapterExpandableWidget 组件 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }
}
